# -*- coding: utf-8 -*-

import json
from public_util.util.AutoUrl import Route
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from package.models import Version, Branch, Project, Task, Handle, Channel, Material


@Route()
def task(request):
    """任务CRUD接口"""
    if request.method == "GET":
        task_type = Task.TASK_TYPE
        state_type = Task.STATE_TYPE
        req = request.REQUEST.get
        init = req("init", 0)
        if init:
            stop_state = Task.STOP_STATE
            pro_objs = Project.filter_project(request)
            bra_objs = Branch.filter_project(request)
            auto_query = True
            return render_to_response("task/task_index.html", locals())
        else:
            task_objs = Task.filter_record(request)
            item_list = []
            for obj in task_objs:
                task_dic = json.loads(obj.task_json)
                item_list.append([obj.get_task_type_display(), obj.project.pro_name,
                                  obj.new_branch if obj.task_type == 1 else obj.branch.branch_name,
                                  obj.progress, obj.get_state_display(),
                                  obj.create_time.strftime("%Y-%m-%d %H:%M:%S"), obj.id])
            return HttpResponse(json.dumps({"aaData": item_list}), content_type="application/json")
    elif request.method == "POST":
        err_msg = ""
        other_dic, handle_info = {}, {}  # other_dict创建Task的参数， handle_info创建操作记录的参数
        task_json = request.post_dic
        task_type = int(request.GET.get("task_type", 0) or 0)
        b_id = int(request.GET.get("id", 0) or 0)
        if b_id:
            b_obj = Branch.objects.filter(id=b_id).first()
            other_dic["project"] = b_obj.project
        else:
            b_obj, other_dic["project"] = None, None
        handle_info["user_id"] = request.admin.id
        handle_info["user"] = request.admin.alias
        handle_info["ope_id"] = task_type
        p_obj = Project.objects.filter(pro_tag=task_json.get("proj_tag")).first()
        handle_info["pro_name"] = p_obj.pro_name
        handle_info["branch_name"] = task_json.get("branch_name")
        if task_type == 1:
            other_dic["project"] = p_obj
            other_dic["new_branch"] = task_json.get("branch_name")
            handle_info["prev_branch"] = task_json.get("prev_branch_name")
        elif task_type in [2, 3, 4]:
            handle_info["os_type"] = task_json.get("plat")
            if task_type == 4 and request.GET.get("redo", 0):
                handle_info["ope_id"] = 11
                v_obj = Version.objects.filter(id=request.GET.get("v_id", 0)).first()
                handle_info["res_svn"] = v_obj.res_svn
        Handle.create_handle(**handle_info)
        Task(
            task_type=task_type, branch=b_obj,
            task_json=json.dumps(task_json, ensure_ascii=False),
            **other_dic
        ).save()
        return render_to_response("feedback.html", locals())
    elif request.method == "PUT":
        err_msg = ""
        params = request.get_dic
        t_id = int(params.pop("id", 0) or 0)
        task_objs = Task.objects.filter(id=t_id)
        if int(params.get("state", 0) or 0) == Task.STOP_STATE:
            t_obj = task_objs.first()
            Handle.create_handle(user_id=request.admin.id, ope_id=6,
                                 user=request.admin.alias,
                                 pro_name=t_obj.branch.project.pro_name if t_obj.task_type != 1 else t_obj.project.pro_name,
                                 branch_name=t_obj.branch.branch_name if t_obj.task_type != 1 else t_obj.new_branch,
                                 task_type=t_obj.get_task_type_display())
        try:
            task_objs.update(**params)
        except Exception as e:
            err_msg = e
        return render_to_response("feedback.html", locals())


@Route()
def pack_pc_detail(request):
    """打包PC详情页面"""
    plat_type = Task.PLAT_TYPE_DICT.get("PC", tuple())
    b_id = request.REQUEST.get("id", 0)
    if b_id:
        model = Branch.objects.filter(id=b_id).first()
    return render_to_response("task/pack_pc_detail.html", locals())


@Route()
def pack_mobile_detail(request):
    """打包移动端详情页面"""
    plat_type = Task.PLAT_TYPE_DICT.get("mobile", tuple())
    b_id = request.REQUEST.get("id", 0)
    if b_id:
        model = Branch.objects.filter(id=b_id).first()
        ver_objs = model.version_set.all()
    return render_to_response("task/pack_mobile_detail.html", locals())


@Route()
def release_version_detail(request):
    """发布版本详情页面"""
    plat_type = Task.PLAT_TYPE_DICT.get("mobile", tuple())
    redo = request.REQUEST.get("redo", 0)
    if redo:
        v_id = request.REQUEST.get("v_id", 0)  # version_id
        v_model = Version.objects.filter(id=v_id).first()
        os_type = v_model.get_os_type_display()
        model = v_model.branch
    else:
        b_id = request.REQUEST.get("b_id", 0)  # branch_id
        if b_id:
            model = Branch.objects.filter(id=b_id).first()
    return render_to_response("task/release_version_detail.html", locals())


@Route()
def open_branch_detail(request):
    """开分支详情页面"""
    pro_bra_dic = {}
    project_objs = Project.filter_project(request)
    for pro_obj in project_objs:
        pro_bra_dic[pro_obj.pro_tag] = [b.branch_name for b in pro_obj.branch_set.all()]
    return render_to_response("task/open_branch_detail.html", locals())


@Route()
def freeze_branch_detail(request):
    """冻结分支详情页面"""
    b_id = request.REQUEST.get("id", 0)
    model = Branch.objects.filter(id=b_id).first()
    return render_to_response("task/freeze_branch_detail.html", locals())


@Route()
def pack_channel_detail(request):
    """打包渠道包详情页面"""
    c_id = request.REQUEST.get("id", 0)
    if c_id:
        model = Channel.objects.filter(id=c_id).first()
        plat = model.get_plat_display()
        branch_name_tuple = model.project.branch_set.all().values_list("id", "branch_name")
        param_folder_lis = Material.objects.filter(
            project_id=model.project.id, channel_id=model.id
        ).values_list("param_folder", flat=True)
    return render_to_response("task/pack_channel_detail.html", locals())


@Route()
def pack_channel_task(request):
    """打包渠道包任务"""
    other_dic = {}  # other_dict创建Task的参数
    task_json = request.post_dic
    task_type = int(request.GET.get("task_type", 0) or 0)

    b_id = task_json.pop("branch_id", "")
    if b_id:
        b_obj = Branch.objects.filter(id=b_id).first()
        if b_obj:
            other_dic["project"] = b_obj.project
            task_json["branch_name"] = b_obj.branch_name
        else:
            err_msg = "分支不存在！"
            return render_to_response("feedback.html", locals())
    else:
        err_msg = "参数缺失！"
        return render_to_response("feedback.html", locals())
    Task(
        task_type=task_type, branch=b_obj,
        task_json=json.dumps(task_json, ensure_ascii=False),
        **other_dic
    ).save()
    return render_to_response("feedback.html", locals())
